package service;

import dataAcsessObject.Exception.NotEntityFoundException;
import dataAcsessObject.JPADAOFactory;
import entity.Role;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import service.exception.ObjectNotFoundException;
import valueObject.RoleVO;

/**
 *
 * @author Juan Hernández Serrato
 */
public class RoleService extends AbstractService<RoleVO, Role> {

    @Override
    public void create(RoleVO valueObject, EntityManager em) {
        JPADAOFactory.getInstance().getRoleDAO().create(valueObject.toEntity(), em);
    }

    @Override
    public void update(RoleVO valueObject, EntityManager em) throws ObjectNotFoundException {
        try {
            Role role = JPADAOFactory.getInstance().getRoleDAO().findById(valueObject.getId(), em);
            role = valueObject.toEntity();
            JPADAOFactory.getInstance().getRoleDAO().update(role, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public void delete(Object id, EntityManager em) throws ObjectNotFoundException {
        try {
            Role role = JPADAOFactory.getInstance().getRoleDAO().findById(id, em);
            JPADAOFactory.getInstance().getRoleDAO().delete(role, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public RoleVO findById(Object id, EntityManager em) throws ObjectNotFoundException {
        try {
            return JPADAOFactory.getInstance().getRoleDAO().findById(id, em).toValueObject();
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public List<RoleVO> findAll(EntityManager em) {
        List<RoleVO> roleVOs = new ArrayList<RoleVO>();
        List<Role> roles = JPADAOFactory.getInstance().getRoleDAO().findAll(em);
        for (Role role : roles) {
            roleVOs.add(role.toValueObject());
        }
        return roleVOs;
    }

    @Override
    public List<RoleVO> findRange(int begin, int end, EntityManager em) {
        List<RoleVO> roleVOs = new ArrayList<RoleVO>();
        List<Role> roles = JPADAOFactory.getInstance().getRoleDAO().findRange(begin, end, em);
        for (Role role : roles) {
            roleVOs.add(role.toValueObject());
        }
        return roleVOs;
    }

}
